package com.haizhi.crm.biz.dao;

import com.haizhi.crm.biz.model.HistoryViewDo;
import com.haizhi.crm.biz.model.VisitRecordResultVo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by yangyijun on 2018/5/10.
 */
@Repository
public interface HistoryViewDao extends JpaRepository<HistoryViewDo, Long> {
    @Query("select new com.haizhi.crm.biz.model.VisitRecordResultVo" +
            "(vr.id, vr.userId,vr.objectKey,vr.productKey,vr.innerEventKey,vr.outerEventKey,vr.customerKey,vr.title,vr.address,vr.recordDesc,vr.visitTimeStart,vr.visitTimeEnd,vr.updatedDt,vr.createdById,u.name,vr.visitorIds,vr.visitRecordId,vr.receiver) " +
            "from HistoryViewDo h " +
            ", com.haizhi.crm.biz.model.VisitRecordDo vr, com.haizhi.crm.sys.auth.model.UserDo u " +
            "where h.userId=:userId and h.entityKey=vr.objectKey and h.entityType='tv_visit_record'  and u.id=vr.userId" )
    List<VisitRecordResultVo> recentViewVisitRecord(@Param("userId" ) Long userId);

    @Query(value = "select * from " +
            "            (select max(id) id,max(user_id) user_id,max(action_type)action_type,max(created_by) created_by,max(h.created_dt) created_dt,max(updated_by) updated_by," +
            "max(h.updated_dt) updated_dt,max(h.enabled_flag)enabled_flag," +
            "h.entity_type,h.entity_key,h.title " +
            "    from tb_history_view h " +
            "    where h.user_id=:userId and h.entity_type=:entityType" +
            "    group by h.entity_type,h.entity_key,h.title " +
            "    )tb " +
            "    order by created_dt desc limit :lit", nativeQuery = true)
    List<HistoryViewDo> findByEntityTypeAndUserId(@Param("userId" ) Long userId, @Param("entityType" ) String entityType, @Param("lit" ) int lit);


    @Query(value = "select * from " +
            "            (select max(id) id,max(user_id) user_id,max(action_type)action_type,max(created_by) created_by,max(h.created_dt) created_dt,max(updated_by) updated_by," +
            "max(h.updated_dt) updated_dt,max(h.enabled_flag)enabled_flag," +
            "h.entity_type,h.entity_key,h.title " +
            "    from tb_history_view h " +
            "    where h.user_id=:userId " +
            "    group by h.entity_type,h.entity_key,h.title " +
            "    )tb " +
            "    order by created_dt desc limit :lit", nativeQuery = true)
    List<HistoryViewDo> findByUserId(@Param("userId" ) Long userId, @Param("lit" ) int lit);

    @Query(value = "select h from HistoryViewDo h where h.entityType=:entityType and h.entityKey=:entityKey and h.userId=:userId" )
    List<HistoryViewDo> findBy(@Param("userId" ) Long userId, @Param("entityType" ) String entityType, @Param("entityKey" ) String entityKey);

}
